package ro.brite.android.opengl.common;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;

import android.opengl.GLSurfaceView.EGLConfigChooser;

public class NiceEGLConfigChooser implements EGLConfigChooser {
	
	public static final String LOG_TAG = "NiceEGLConfigChooser";

	private int[] attrib_list = {
		EGL10.EGL_RED_SIZE, 8,
		EGL10.EGL_GREEN_SIZE, 8,
		EGL10.EGL_BLUE_SIZE, 8,
		EGL10.EGL_ALPHA_SIZE, 8,
		EGL10.EGL_DEPTH_SIZE, 16,
		EGL10.EGL_STENCIL_SIZE, 0,
		EGL10.EGL_BUFFER_SIZE, 4,
		EGL10.EGL_SAMPLE_BUFFERS, 1,
		EGL10.EGL_SAMPLES, 4,
		EGL10.EGL_NONE
	};
	
	private int[] num = new int[1];
	private int[] mValue = new int[1];

	@Override
	public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
		egl.eglChooseConfig(display, attrib_list, null, 0, num);
//		Log.i(LOG_TAG, "num :" + num[0]);
		EGLConfig mcConfig[] = new EGLConfig[num[0]];
		egl.eglChooseConfig(display, attrib_list, mcConfig, num[0], num);

		return chooseConfig(egl, display, mcConfig);
	}

	@SuppressWarnings("unused")
	private EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) {
		for (EGLConfig config : configs) {
			int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
			int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
			if ((d >= 16) && (s >= 0)) {
				int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
				int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
				int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
				int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
				int bz = findConfigAttrib(egl, display, config, EGL10.EGL_BUFFER_SIZE, 0);
				int sb = findConfigAttrib(egl, display, config, EGL10.EGL_SAMPLE_BUFFERS, 0);
				int sa = findConfigAttrib(egl, display, config, EGL10.EGL_SAMPLES, 0);
//				Log.i(LOG_TAG, "bz :" + bz + " sb :" + sb + " sa :" + sa);
				if ((r == 8) && (g == 8) && (b == 8) && (a == 8) && (sb >= 1) && (sa >= 4)) {
					return config;
				}
			}
		}
		return null;
	}

	private int findConfigAttrib(EGL10 egl, EGLDisplay display,
			EGLConfig config, int attribute, int defaultValue) {
		if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
			return mValue[0];
		}
		return defaultValue;
	}
}
